const express = require('express');
const router = express.Router();
const User = require('../models/User');
const { generateToken, authenticateToken } = require('../middleware/auth');
const { validateUserRegistration, validateUserLogin } = require('../middleware/validation');

// 用户注册
router.post('/register', validateUserRegistration, async (req, res) => {
  try {
    const { username, password, email, nickname, phone } = req.body;
    
    const user = await User.create({
      username,
      password,
      email,
      nickname,
      phone
    });
    
    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          nickname: user.nickname,
          avatar_url: user.avatar_url,
          phone: user.phone,
          created_at: user.created_at
        }
      }
    });
  } catch (error) {
    console.error('注册错误:', error);
    
    if (error.message === '用户名已存在' || error.message === '邮箱已存在') {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试'
    });
  }
});

// 用户登录
router.post('/login', validateUserLogin, async (req, res) => {
  try {
    const { username, password } = req.body;
    
    const user = await User.validateLogin(username, password);
    
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }
    
    // 生成JWT token
    const token = generateToken(user.id);
    
    res.json({
      success: true,
      message: '登录成功',
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          nickname: user.nickname,
          avatar_url: user.avatar_url,
          phone: user.phone,
          created_at: user.created_at,
          last_login_at: user.last_login_at
        },
        token
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试'
    });
  }
});

// 获取当前用户信息
router.get('/me', authenticateToken, async (req, res) => {
  try {
    res.json({
      success: true,
      data: {
        user: {
          id: req.user.id,
          username: req.user.username,
          email: req.user.email,
          nickname: req.user.nickname,
          avatar_url: req.user.avatar_url,
          phone: req.user.phone,
          status: req.user.status,
          created_at: req.user.created_at,
          updated_at: req.user.updated_at,
          last_login_at: req.user.last_login_at
        }
      }
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
});

// 更新用户信息
router.put('/me', authenticateToken, async (req, res) => {
  try {
    const { email, nickname, phone } = req.body;
    
    const updatedUser = await User.update(req.user.id, {
      email,
      nickname,
      phone
    });
    
    res.json({
      success: true,
      message: '用户信息更新成功',
      data: {
        user: updatedUser
      }
    });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    
    if (error.message === '邮箱已存在') {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '更新用户信息失败'
    });
  }
});

// 修改密码
router.put('/password', authenticateToken, async (req, res) => {
  try {
    const { oldPassword, newPassword } = req.body;
    
    if (!oldPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '原密码和新密码不能为空'
      });
    }
    
    if (newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码长度至少6位'
      });
    }
    
    await User.changePassword(req.user.id, oldPassword, newPassword);
    
    res.json({
      success: true,
      message: '密码修改成功'
    });
  } catch (error) {
    console.error('修改密码错误:', error);
    
    if (error.message === '原密码错误') {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '修改密码失败'
    });
  }
});

// 退出登录（客户端处理，服务端可以记录日志）
router.post('/logout', authenticateToken, async (req, res) => {
  try {
    // 这里可以添加退出登录的日志记录
    // 如果使用了session或需要黑名单token，可以在这里处理
    
    res.json({
      success: true,
      message: '退出登录成功'
    });
  } catch (error) {
    console.error('退出登录错误:', error);
    res.status(500).json({
      success: false,
      message: '退出登录失败'
    });
  }
});

// 验证token有效性
router.get('/verify', authenticateToken, async (req, res) => {
  res.json({
    success: true,
    message: 'Token有效',
    data: {
      user: {
        id: req.user.id,
        username: req.user.username,
        nickname: req.user.nickname
      }
    }
  });
});

module.exports = router;
